package me.macd.mindoc.dao.impl;

import me.macd.mindoc.dao.DocumentDao;
import me.macd.mindoc.model.Documents;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: mindoc
 * @description: ${description}
 * @author: 2018-10-10
 * @create: 2018-10-10 20:33
 */
@Repository
public class DocumentDaoJDBCTemplateImpl implements DocumentDao {

    private final JdbcTemplate jdbcTemplate;

    @Autowired
    public DocumentDaoJDBCTemplateImpl(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    public Map<String, Object> modifyInfo(int bookId) {
        String sql = "SELECT m.account,doc.modify_time FROM md_documents AS doc" +
                " LEFT JOIN md_members AS m ON doc.modify_at=m.member_id" +
                " WHERE book_id = ? ORDER BY doc.modify_time DESC LIMIT 1";

        return jdbcTemplate.queryForObject(sql, new RowMapper<Map<String, Object>>() {
            @Nullable
            @Override
            public Map<String, Object> mapRow(ResultSet rs, int rowNum) throws SQLException {
                Map<String, Object> map = new HashMap<>();
                Object account = rs.getObject("account");
                if (account == null) {
                    map.put("account", "");
                } else {
                    map.put("account", account.toString());
                }

                map.put("modify_time", rs.getTimestamp("modify_time"));
                return map;
            }
        }, bookId);
    }

    @Override
    public int insert(Documents document) {
        return new CommonDao(jdbcTemplate).insert(document);
    }
}
